<?php

namespace app\admin\controller;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="达人动态列表")
 */
class Dynamic extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Dynamic();
        
    }
  /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
                foreach ($list as $k => $v){
                   
                    //达人
                    $service_technician = Db::name("service_technician")->where("id",$v["service_technician_id"])->field("service_name,phone")->find();
                    if(!empty($service_technician)){
                        $v["service_technician_name"] = $service_technician["service_name"];
                    }else{
                        $v["service_technician_name"] = "";
                    }
                    

                    $list[$k] = $v;
                }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

  

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        //达人
        $service_technician = Db::name("service_technician")->where("id",$row["service_technician_id"])->field("service_name,phone")->find();
        if(!empty($service_technician)){
            $row["service_technician_name"] = $service_technician["service_name"];
        }else{
            $row["service_technician_name"] = "";
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    
}